home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 52 / Amiga Format AFCD52 (Issue 136, May 2000).iso / -serious- / programming / c / icu-1.3.1 / icu-bin / include / datefmt.h < prev    next >
C/C++ Source or Header  |  2000-02-23  |  23KB  |  540 lines

  1. /*
  2. ********************************************************************************
  3. *                                                                              *
  4. * COPYRIGHT:                                                                   *
  5. *   (C) Copyright Taligent, Inc.,  1997                                        *
  6. *   (C) Copyright International Business Machines Corporation,  1997-1999      *
  7. *   Copyright (C) 1999 Alan Liu and others. All rights reserved.               *
  8. *   Licensed Material - Program-Property of IBM - All Rights Reserved.         *
  9. *   US Government Users Restricted Rights - Use, duplication, or disclosure    *
  10. *   restricted by GSA ADP Schedule Contract with IBM Corp.                     *
  11. *                                                                              *
  12. ********************************************************************************
  13. *
  14. * File DATEFMT.H
  15. *
  16. * Modification History:
  17. *
  18. *   Date        Name        Description
  19. *   02/19/97    aliu        Converted from java.
  20. *   04/01/97    aliu        Added support for centuries.
  21. *    07/23/98    stephen        JDK 1.2 sync
  22. ********************************************************************************
  23. */
  24.  
  25. #ifndef DATEFMT_H
  26. #define DATEFMT_H
  27.  
  28. #include "utypes.h"
  29. #include "calendar.h"
  30. #include "numfmt.h"
  31. #include "format.h"
  32. #include "locid.h"
  33. class TimeZone;
  34.  
  35. /**
  36.  * DateFormat is an abstract class for a family of classes that convert dates and
  37.  * times from their internal representations to textual form and back again in a
  38.  * language-independent manner. Converting from the internal representation (milliseconds
  39.  * since midnight, January 1, 1970) to text is known as "formatting," and converting
  40.  * from text to millis is known as "parsing."  We currently define only one concrete
  41.  * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal
  42.  * date formatting and parsing actions.
  43.  * <P>
  44.  * DateFormat helps you to format and parse dates for any locale. Your code can
  45.  * be completely independent of the locale conventions for months, days of the
  46.  * week, or even the calendar format: lunar vs. solar.
  47.  * <P>
  48.  * To format a date for the current Locale, use one of the static factory
  49.  * methods:
  50.  * <pre>
  51.  * .    DateFormat* dfmt = DateFormat::createDateInstance();
  52.  * .    UnicodeString myString;
  53.  * .    myString = dfmt->format( myDate, myString );
  54.  * </pre>
  55.  * If you are formatting multiple numbers, it is more efficient to get the
  56.  * format and use it multiple times so that the system doesn't have to fetch the
  57.  * information about the local language and country conventions multiple times.
  58.  * <pre>
  59.  * .    DateFormat* df = DateFormat::createDateInstance();
  60.  * .    UnicodeString myString;
  61.  * .    UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
  62.  * .    for (int32_t i = 0; i < 3; ++i) {
  63.  * .        myString.remove();
  64.  * .        cout << df->format( myDateArr[i], myString ) << endl;
  65.  * .    }
  66.  * </pre>
  67.  * To format a date for a different Locale, specify it in the call to
  68.  * getDateInstance().
  69.  * <pre>
  70.  * .       DateFormat* df =
  71.  * .          DateFormat::createDateInstance( DateFormat::SHORT, Locale::FRANCE);
  72.  * </pre>
  73.  * You can use a DateFormat to parse also.
  74.  * <pre>
  75.  * .       UErrorCode status = U_ZERO_ERROR;
  76.  * .       UDate myDate = df->parse(myString, status);
  77.  * </pre>
  78.  * Use createDateInstance() to produce the normal date format for that country.
  79.  * There are other static factory methods available. Use createTimeInstance()
  80.  * to produce the normal time format for that country. Use createDateTimeInstance()
  81.  * to produce a DateFormat that formats both date and time. You can pass in
  82.  * different options to these factory methods to control the length of the
  83.  * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the
  84.  * locale, but generally:
  85.  * <ul type=round>
  86.  *   <li>   SHORT is completely numeric, such as 12/13/52 or 3:30pm
  87.  *   <li>   MEDIUM is longer, such as Jan 12, 1952
  88.  *   <li>   LONG is longer, such as January 12, 1952 or 3:30:32pm
  89.  *   <li>   FULL is pretty completely specified, such as
  90.  *          Tuesday, April 12, 1952 AD or 3:30:42pm PST.
  91.  * </ul>
  92.  * You can also set the time zone on the format if you wish. If you want even
  93.  * more control over the format or parsing, (or want to give your users more
  94.  * control), you can try casting the DateFormat you get from the factory methods
  95.  * to a SimpleDateFormat. This will work for the majority of countries; just
  96.  * remember to chck getDynamicClassID() before carrying out the cast.
  97.  * <P>
  98.  * You can also use forms of the parse and format methods with ParsePosition and
  99.  * FieldPosition to allow you to
  100.  * <ul type=round>
  101.  *   <li>   Progressively parse through pieces of a string.
  102.  *   <li>   Align any particular field, or find out where it is for selection
  103.  *          on the screen.
  104.  * </ul>
  105.  */
  106. class U_I18N_API DateFormat : public Format {
  107. public:
  108.     /**
  109.      * The following enum values are used in FieldPosition with date/time formatting.
  110.      * They are also used to index into DateFormatSymbols::fgPatternChars, which
  111.      * is the list of standard internal-representation pattern characters, and
  112.      * the resource bundle localPatternChars data. For this reason, this enum
  113.      * should be treated with care; don't change the order or contents of it
  114.      * unless you really know what you are doing. You'll probably have to change
  115.      * the code in DateFormatSymbols, SimpleDateFormat, and all the locale
  116.      * resource bundle data files.
  117.      */
  118.     enum EField
  119.     {
  120.         kEraField,          // ERA field alignment.
  121.         kYearField,         // YEAR field alignment.
  122.         kMonthField,        // MONTH field alignment.
  123.         kDateField,         // DATE field alignment.
  124.         kHourOfDay1Field,     // One-based HOUR_OF_DAY field alignment.
  125.                             // kHourOfDay1Field is used for the one-based 24-hour clock.
  126.                             // For example, 23:59 + 01:00 results in 24:59.
  127.         kHourOfDay0Field,     // Zero-based HOUR_OF_DAY field alignment.
  128.                             // HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
  129.                             // For example, 23:59 + 01:00 results in 00:59.
  130.         kMinuteField,       // MINUTE field alignment.
  131.         kSecondField,       // SECOND field alignment.
  132.         kMillisecondField,  // MILLISECOND field alignment.
  133.         kDayOfWeekField,      // DAY_OF_WEEK field alignment.
  134.         kDayOfYearField,      // DAY_OF_YEAR field alignment.
  135.         kDayOfWeekInMonthField,// DAY_OF_WEEK_IN_MONTH field alignment.
  136.         kWeekOfYearField,     // WEEK_OF_YEAR field alignment.
  137.         kWeekOfMonthField,    // WEEK_OF_MONTH field alignment.
  138.         kAmPmField,            // AM_PM field alignment.
  139.         kHour1Field,        // One-based HOUR field alignment.
  140.                             // HOUR1_FIELD is used for the one-based 12-hour clock.
  141.                             // For example, 11:30 PM + 1 hour results in 12:30 AM.
  142.         kHour0Field,        // Zero-based HOUR field alignment.
  143.                             // HOUR0_FIELD is used for the zero-based 12-hour clock.
  144.                             // For example, 11:30 PM + 1 hour results in 00:30 AM.
  145.         kTimezoneField,      // TIMEZONE field alignment.
  146.         
  147.         
  148.     /**
  149.      * These constants are provided for backwards compatibility only,
  150.      * and are deprecated.  Please use the C++ style constants defined above.
  151.      */
  152.         ERA_FIELD                     = kEraField,
  153.         YEAR_FIELD                     = kYearField,
  154.         MONTH_FIELD                 = kMonthField,
  155.         DATE_FIELD                     = kDateField,
  156.         HOUR_OF_DAY1_FIELD             = kHourOfDay1Field,
  157.         HOUR_OF_DAY0_FIELD             = kHourOfDay0Field,
  158.         MINUTE_FIELD                 = kMinuteField,
  159.         SECOND_FIELD                 = kSecondField,
  160.         MILLISECOND_FIELD             = kMillisecondField,
  161.         DAY_OF_WEEK_FIELD             = kDayOfWeekField,
  162.         DAY_OF_YEAR_FIELD             = kDayOfYearField,
  163.         DAY_OF_WEEK_IN_MONTH_FIELD     = kDayOfWeekInMonthField,
  164.         WEEK_OF_YEAR_FIELD             = kWeekOfYearField,
  165.         WEEK_OF_MONTH_FIELD         = kWeekOfMonthField,
  166.         AM_PM_FIELD                 = kAmPmField,
  167.         HOUR1_FIELD                 = kHour1Field,
  168.         HOUR0_FIELD                 = kHour0Field,
  169.         TIMEZONE_FIELD                 = kTimezoneField
  170.  
  171.     };
  172.  
  173.     /**
  174.      * Constants for various style patterns. These reflect the order of items in
  175.      * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns,
  176.      * and then the date-time pattern. Each block of 4 values in the resource occurs
  177.      * in the order full, long, medium, short.
  178.      */
  179.     enum EStyle
  180.     {
  181.         kFull,
  182.         kLong,
  183.         kMedium,
  184.         kShort,
  185.  
  186.         kDefault     = kMedium,
  187.         kDateOffset = 4,
  188.         kNone         = -1,
  189.         kDateTime     = 8,
  190.         
  191.         
  192.     /**
  193.      * These constants are provided for backwards compatibility only,
  194.      * and are deprecated.  Please use the C++ style constants defined above.
  195.      */       
  196.         FULL        = kFull,
  197.         LONG        = kLong,
  198.         MEDIUM        = kMedium,
  199.         SHORT        = kShort,
  200.         DEFAULT        = kDefault,
  201.         DATE_OFFSET    = kDateOffset,
  202.         NONE        = kNone,
  203.         DATE_TIME    = kDateTime
  204.     };
  205.  
  206.     /**
  207.      * Destructor.
  208.      */
  209.     virtual ~DateFormat();
  210.  
  211.     /**
  212.      * Equality operator.  Returns true if the two formats have the same behavior.
  213.      */
  214.     virtual bool_t operator==(const Format&) const;
  215.  
  216.     /**
  217.      * Format an object to produce a string. This method handles Formattable
  218.      * objects with a UDate type. If a the Formattable object type is not a Date,
  219.      * then it returns a failing UErrorCode.
  220.      *
  221.      * @param obj           The object to format. Must be a Date.
  222.      * @param toAppendTo    The result of the formatting operation is appended to
  223.      *                      this string.
  224.      * @param pos           On input: an alignment field, if desired.
  225.      *                      On output: the offsets of the alignment field.
  226.      * @param status        Output param filled with success/failure status.
  227.      * @return              The value passed in as toAppendTo (this allows chaining,
  228.      *                      as with UnicodeString::append())
  229.      */
  230.     virtual UnicodeString& format(const Formattable& obj,
  231.                                   UnicodeString& toAppendTo,
  232.                                   FieldPosition& pos,
  233.                                   UErrorCode& status) const;
  234.  
  235.     /**
  236.      * Formats a UDate into a date/time string. This is an abstract method which
  237.      * concrete subclasses must implement.
  238.      * <P>
  239.      * On input, the FieldPosition parameter may have its "field" member filled with
  240.      * an enum value specifying a field.  On output, the FieldPosition will be filled
  241.      * in with the text offsets for that field.  
  242.      * <P> For example, given a time text
  243.      * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
  244.      * DateFormat::kYearField, the offsets fieldPosition.beginIndex and
  245.      * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. 
  246.      * <P> Notice
  247.      * that if the same time field appears more than once in a pattern, the status will
  248.      * be set for the first occurence of that time field. For instance,
  249.      * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
  250.      * using the pattern "h a z (zzzz)" and the alignment field
  251.      * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
  252.      * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
  253.      * occurence of the timezone pattern character 'z'.
  254.      *
  255.      * @param date          a UDate to be formatted into a date/time string.
  256.      * @param toAppendTo    the result of the formatting operation is appended to
  257.      *                      the end of this string.
  258.      * @param fieldPosition On input: an alignment field, if desired (see examples above)
  259.      *                      On output: the offsets of the alignment field (see examples above)
  260.      * @return              A reference to 'toAppendTo'.
  261.      */
  262.     virtual UnicodeString& format(  UDate date,
  263.                                     UnicodeString& toAppendTo,
  264.                                     FieldPosition& fieldPosition) const = 0;
  265.  
  266.     /**
  267.      * Formats a UDate into a date/time string. If there is a problem, you won't
  268.      * know, using this method. Use the overloaded format() method which takes a
  269.      * FieldPosition& to detect formatting problems.
  270.      *
  271.      * @param date      The UDate value to be formatted into a string.
  272.      * @param result    Output param which will receive the formatted date.
  273.      * @return          A reference to 'result'.
  274.      */
  275.     UnicodeString& format(UDate date, UnicodeString& result) const;
  276.  
  277.     /**
  278.      * Redeclared Format method.
  279.      */
  280.     UnicodeString& format(const Formattable& obj,
  281.                           UnicodeString& result,
  282.                           UErrorCode& status) const;
  283.  
  284.     /**
  285.      * Parse a date/time string.
  286.      *
  287.      * @param text      The string to be parsed into a UDate value.
  288.      * @param status    Output param to be set to success/failure code. If
  289.      *                  'text' cannot be parsed, it will be set to a failure
  290.      *                  code.
  291.      * @result          The parsed UDate value, if successful.
  292.      */
  293.     virtual UDate parse( const UnicodeString& text,
  294.                         UErrorCode& status) const;
  295.  
  296.     /**
  297.      * Parse a date/time string beginning at the given parse position. For
  298.      * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
  299.      * that is equivalent to Date(837039928046).
  300.      * <P>
  301.      * By default, parsing is lenient: If the input is not in the form used by
  302.      * this object's format method but can still be parsed as a date, then the
  303.      * parse succeeds. Clients may insist on strict adherence to the format by
  304.      * calling setLenient(false).
  305.      *
  306.      * @see DateFormat::setLenient(boolean)
  307.      *
  308.      * @param text  The date/time string to be parsed
  309.      * @param pos   On input, the position at which to start parsing; on
  310.      *              output, the position at which parsing terminated, or the
  311.      *              start position if the parse failed.
  312.      * @return      A valid UDate if the input could be parsed.
  313.      */
  314.     virtual UDate parse( const UnicodeString& text,
  315.                         ParsePosition& pos) const = 0;
  316.  
  317.     /**
  318.      * Parse a string to produce an object. This methods handles parsing of
  319.      * date/time strings into Formattable objects with UDate types.
  320.      * <P>
  321.      * Before calling, set parse_pos.index to the offset you want to start
  322.      * parsing at in the source. After calling, parse_pos.index is the end of
  323.      * the text you parsed. If error occurs, index is unchanged.
  324.      * <P>
  325.      * When parsing, leading whitespace is discarded (with a successful parse),
  326.      * while trailing whitespace is left as is.
  327.      * <P>
  328.      * See Format::parseObject() for more.
  329.      *
  330.      * @param source    The string to be parsed into an object.
  331.      * @param result    Formattable to be set to the parse result.
  332.      *                  If parse fails, return contents are undefined.
  333.      * @param parse_pos The position to start parsing at. Upon return
  334.      *                  this param is set to the position after the
  335.      *                  last character successfully parsed. If the
  336.      *                  source is not parsed successfully, this param
  337.      *                  will remain unchanged.
  338.      * @return          A newly created Formattable* object, or NULL
  339.      *                  on failure.  The caller owns this and should
  340.      *                  delete it when done.
  341.      */
  342.     virtual void parseObject(const UnicodeString& source,
  343.                              Formattable& result,
  344.                              ParsePosition& parse_pos) const;
  345.  
  346.     /**
  347.      * Create a default date/time formatter that uses the SHORT style for both
  348.      * the date and the time.
  349.      *
  350.      * @return A date/time formatter which the caller owns.
  351.      */
  352.     static DateFormat* createInstance(void);
  353.  
  354.     /**
  355.      * Creates a time formatter with the given formatting style for the given
  356.      * locale.
  357.      * 
  358.      * @param style     The given formatting style. For example,
  359.      *                  SHORT for "h:mm a" in the US locale.
  360.      * @param aLocale   The given locale.
  361.      * @return          A time formatter which the caller owns.
  362.      */
  363.     static DateFormat* createTimeInstance(EStyle style = kDefault,
  364.                                           const Locale& aLocale = Locale::getDefault());
  365.  
  366.     /**
  367.      * Creates a date formatter with the given formatting style for the given
  368.      * const locale.
  369.      * 
  370.      * @param style     The given formatting style. For example,
  371.      *                  SHORT for "M/d/yy" in the US locale.
  372.      * @param aLocale   The given locale.
  373.      * @return          A date formatter which the caller owns.
  374.      */
  375.     static DateFormat* createDateInstance(EStyle style = kDefault,
  376.                                           const Locale& aLocale = Locale::getDefault());
  377.  
  378.     /**
  379.      * Creates a date/time formatter with the given formatting styles for the
  380.      * given locale.
  381.      * 
  382.      * @param dateStyle The given formatting style for the date portion of the result.
  383.      *                  For example, SHORT for "M/d/yy" in the US locale.
  384.      * @param timeStyle The given formatting style for the time portion of the result.
  385.      *                  For example, SHORT for "h:mm a" in the US locale.
  386.      * @param aLocale   The given locale.
  387.      * @return          A date/time formatter which the caller owns.
  388.      */
  389.     static DateFormat* createDateTimeInstance(EStyle dateStyle = kDefault,
  390.                                               EStyle timeStyle = kDefault,
  391.                                               const Locale& aLocale = Locale::getDefault());
  392.  
  393.     /**
  394.      * Gets the set of locales for which DateFormats are installed.
  395.      * @param count Filled in with the number of locales in the list that is returned.
  396.      * @return the set of locales for which DateFormats are installed.  The caller
  397.      *  does NOT own this list and must not delete it.
  398.      */
  399.     static const Locale* getAvailableLocales(int32_t& count);
  400.   
  401.     /**
  402.      * Returns true if the formatter is set for lenient parsing.
  403.      */
  404.     virtual bool_t isLenient(void) const;
  405.  
  406.     /**
  407.      * Specify whether or not date/time parsing is to be lenient. With lenient
  408.      * parsing, the parser may use heuristics to interpret inputs that do not
  409.      * precisely match this object's format. With strict parsing, inputs must
  410.      * match this object's format.
  411.      * @see Calendar::setLenient
  412.      */
  413.     virtual void setLenient(bool_t lenient);
  414.     
  415.     /**
  416.      * Gets the calendar associated with this date/time formatter.
  417.      * @return the calendar associated with this date/time formatter.
  418.      */
  419.     virtual const Calendar* getCalendar(void) const;
  420.     
  421.     /**
  422.      * Set the calendar to be used by this date format. Initially, the default
  423.      * calendar for the specified or default locale is used.  The caller should
  424.      * not delete the Calendar object after it is adopted by this call.
  425.      */
  426.     virtual void adoptCalendar(Calendar* calendarToAdopt);
  427.  
  428.     /**
  429.      * Set the calendar to be used by this date format. Initially, the default
  430.      * calendar for the specified or default locale is used.
  431.      */
  432.     virtual void setCalendar(const Calendar& newCalendar);
  433.  
  434.    
  435.     /**
  436.      * Gets the number formatter which this date/time formatter uses to format
  437.      * and parse the numeric portions of the pattern.
  438.      * @return the number formatter which this date/time formatter uses.
  439.      */
  440.     virtual const NumberFormat* getNumberFormat(void) const;
  441.     
  442.     /**
  443.      * Allows you to set the number formatter.  The caller should
  444.      * not delete the NumberFormat object after it is adopted by this call.
  445.      * @param formatToAdopt     NumberFormat object to be adopted.
  446.      */
  447.     virtual void adoptNumberFormat(NumberFormat* formatToAdopt);
  448.  
  449.     /**
  450.      * Allows you to set the number formatter.
  451.      * @param formatToAdopt     NumberFormat object to be adopted.
  452.      */
  453.     virtual void setNumberFormat(const NumberFormat& newNumberFormat);
  454.  
  455.     /**
  456.      * Returns a reference to the TimeZone used by this DateFormat's calendar.
  457.      * @return the time zone associated with the calendar of DateFormat.
  458.      */
  459.     virtual const TimeZone& getTimeZone(void) const;
  460.     
  461.     /**
  462.      * Sets the time zone for the calendar of this DateFormat object. The caller
  463.      * no longer owns the TimeZone object and should not delete it after this call.
  464.      * @param zone the new time zone.
  465.      */
  466.     virtual void adoptTimeZone(TimeZone* zoneToAdopt);
  467.  
  468.     /**
  469.      * Sets the time zone for the calendar of this DateFormat object.
  470.      * @param zone the new time zone.
  471.      */
  472.     virtual void setTimeZone(const TimeZone& zone);
  473.  
  474.     
  475. protected:
  476.     /**
  477.      * Default constructor.  Creates a DateFormat with no Calendar or NumberFormat
  478.      * associated with it.  This constructor depends on the subclasses to fill in
  479.      * the calendar and numberFormat fields.
  480.      */
  481.     DateFormat();
  482.  
  483.     /**
  484.      * Copy constructor.
  485.      */
  486.     DateFormat(const DateFormat&);
  487.  
  488.     /**
  489.      * Default assignment operator.
  490.      */
  491.     DateFormat& operator=(const DateFormat&);
  492.  
  493.     /**
  494.      * The calendar that DateFormat uses to produce the time field values needed
  495.      * to implement date/time formatting. Subclasses should generally initialize
  496.      * this to the default calendar for the locale associated with this DateFormat.
  497.      */
  498.     Calendar* fCalendar;
  499.  
  500.     /**
  501.      * The number formatter that DateFormat uses to format numbers in dates and
  502.      * times. Subclasses should generally initialize this to the default number
  503.      * format for the locale associated with this DateFormat.
  504.      */
  505.     NumberFormat* fNumberFormat;
  506.  
  507. private:
  508.     /**
  509.      * Gets the date/time formatter with the given formatting styles for the
  510.      * given locale.
  511.      * @param dateStyle the given date formatting style.
  512.      * @param timeStyle the given time formatting style.
  513.      * @param inLocale the given locale.
  514.      * @return a date/time formatter, or 0 on failure.
  515.      */
  516.     static DateFormat* create(EStyle timeStyle, EStyle dateStyle, const Locale&);
  517.  
  518.     /**
  519.      * fgLocales and fgLocalesCount cache the available locales array that is returned
  520.      * by getAvailableLocales().
  521.      */
  522.     static int32_t          fgLocalesCount;
  523.  
  524.     /**
  525.      * fgLocales and fgLocalesCount cache the available locales array that is returned
  526.      * by getAvailableLocales().
  527.      */
  528.     static const Locale*    fgLocales;
  529. };
  530.  
  531. inline UnicodeString&
  532. DateFormat::format(const Formattable& obj,
  533.                    UnicodeString& result,
  534.                    UErrorCode& status) const {
  535.     return Format::format(obj, result, status);
  536. }
  537.  
  538. #endif // _DATEFMT
  539. //eof
  540.